# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.


from odoo import api, fields, models, _

from .check_zncspt import check_fapiao
from .check_zncspt import access_token_check
import datetime

import logging

_logger = logging.getLogger(__name__)


def zncspt_check_method(fapiao):
    # print('zncspt_check_method', fapiao)
    result = check_fapiao(fapiao)

    for rec in result:
        one = fapiao.browse(rec['id'])
        # print('zncspt_check_method. 2.', rec)

        api_check_result = rec['api_check_result']
        api_check_result_info = rec['api_check_result_info']

        values = {
            'zncspt_api_check_result': api_check_result,
            'zncspt_api_check_result_info': api_check_result_info,
        }

        if api_check_result == 'done':
            # one.state  = one['state'] # done, refunded, be_invalid

            api_check_date = rec['api_check_date']
            api_check_count = rec['api_check_count']
            api_list_flag = rec['api_list_flag']

            values.update({
                'zncspt_api_check_date': api_check_date,
                'zncspt_api_check_count': api_check_count,
                'zncspt_api_list_flag': api_list_flag,
            })

        else:
            check_error = api_check_result[0:9]
            if check_error == 'fpi_error':
                values['state'] = rec['state'] = 'error'
            elif check_error == 'api_error':
                values['state'] = 'recheck'
                rec['state'] = 'recheck'

        one.write(values)

    return result


class FapiaoApiCheck(models.Model):
    _inherit = "fp.api.check"

    def _request_methods(self):
        result = super()._request_methods()
        result2 = result.copy()
        result2.update({'zncspt': zncspt_check_method})
        return result2


class ApiCheckCompany(models.Model):
    _inherit = "fp.api.check.company"

    zncspt_app_key = fields.Char(string='zncspt App Key')
    zncspt_app_secret = fields.Char(string='zncspt App Secret')

    zncspt_access_token = fields.Char(string='zncspt Access Token')
    zncspt_expires_in = fields.Integer(string='zncspt Expires_in')
    zncspt_lasttime = fields.Datetime(string='zncspt Lasttime')

    def zncspt_access_token_check(self):
        res = access_token_check(self)
        _logger.info("Nuonuo Token is checked: %s" % res)

        if res:
            now = datetime.datetime.now()
            self.write({
                'zncspt_access_token': res['access_token'],
                'zncspt_expires_in': res['expires_in'],
                'zncspt_lasttime': now.strftime('%Y-%m-%d %H:%M:%S'),
            })

        return res
